from rest_framework import serializers

from user_app.models import User


class UserSerializer(serializers.ModelSerializer):
    groups_names = serializers.StringRelatedField(many=True, source='groups',
                                                  read_only=True)
    user_permissions_names = serializers.StringRelatedField(many=True,
                                                            source='user_permissions',
                                                            read_only=True)

    # instance.user_permissions.all()
    class Meta:
        fields = ['id', 'username', 'mobile', 'email', 'password', 'groups',
                  'user_permissions', 'groups_names', 'user_permissions_names']
        model = User

        # 定义检查器 检查输入数据是否符合要求
        extra_kwargs = {
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            },
            'username': {
                'max_length': 20,
                'min_length': 5,
            },
            'groups': {
                "write_only": True
            },
            'user_permissions': {
                "write_only": True
            }
        }

    def create(self, validated_data):
        instance = super().create(validated_data)
        instance.set_password(validated_data['password'])
        instance.is_staff = True
        instance.save()
        return instance

    def update(self, instance, validated_data):
        instance = super().update(instance, validated_data)
        instance.set_password(validated_data['password'])
        instance.save()
        return instance
